/*
 * > /*
>  * INSANE - Interactive Structural Analysis Environment
>  *
>  * Copyright (C) 2003-2004
>  * Universidade Federal de Minas Gerais
>  * Escola de Engenharia
>  * Departamento de Engenharia de Estruturas
>  *
>  * Author's email :     insane@dees.ufmg.br
>  * Author's Website :   http://www.dees.ufmg.br/insane
>  *
>  * This program is free software; you can redistribute it and/or
>  * modify it under the terms of the GNU General Public License
>  * as published by the Free Software Foundation; either version 2
>  * of the License, or any later version.
>  *
>  * This program is distributed in the hope that it will be useful,
>  * but WITHOUT ANY WARRANTY; without even the implied warranty of
>  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
>  * GNU General Public License for more details.
>  *
>  * You should have received a copy of the GNU General Public License
>  * along with this program; if not, write to the Free Software
>  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-
> 1307, USA.
 *
 */

package br.ufmg.dees.insane.ui.rich.prep.view.dialog;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Locale;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JInternalFrame;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

import br.ufmg.dees.insane.commons.dialogs.SimpleDialog;
import br.ufmg.dees.insane.model.prep.GeoPrepModel;
import br.ufmg.dees.insane.ui.rich.prep.view.DesktopPrep;
import br.ufmg.dees.insane.ui.rich.prep.view.InterfacePrep;
import br.ufmg.dees.insane.ui.rich.prep.view.command.TileViewCommand;

/**
 * A class representing creation dialog on screen.<br>
 * @author Ferreira, Reginaldo & Pitangueira, Roque
 * @since october 2006
 */
public final class ModelSelectionDialog extends SimpleDialog {

    /**
	 * Comment for <code>serialVersionUID</code>
	 */
	private static final long serialVersionUID = 1L;
	private DesktopPrep desktop;
    
	private JPanel panelModel = new JPanel();
	private JPanel panelView = new JPanel();
	private JPanel panelButton = new JPanel();
	private JList  panelViewList, panelModelList;
	
	private JButton toFrontBtn, closeViewBtn, addViewBtn, deleteModelBtn,
	                renameViewBtn, closeAllViewBtn;
	private JScrollPane panelScrollView, panelScrollModel;
	
	private int nViewsDtk, nViewsMdl, nModels;
	
	private String[] modelNames, modelViewsName;
	
	private GeoPrepModel current;
	
	JInternalFrame desktopViews[];
	
    private NumberFormat numberFormat;
    
//  ****************************************************************************
	
    /**
     * Constructor method, calling super with the especific title.
     *
     * @param parent The parent of the class.
     * @see gui.Interface
     */
    public ModelSelectionDialog(DesktopPrep parent)
    {
        this.desktop = parent;

        if (desktop.getModelList().size() == 0)
        	current = null;
        else
        	current = (GeoPrepModel)desktop.getModelList().get(0);
        
        setUpFormat();

        JPanel mainPane = new JPanel();
        mainPane.setLayout(new BorderLayout());
        mainPane.add(getPanelModel(),  BorderLayout.WEST);
        mainPane.add(getPanelView(),   BorderLayout.EAST);
        mainPane.add(getPanelButton(), BorderLayout.SOUTH);
        setPane(mainPane);
        
        // listeners
        addViewBtn.addActionListener(
				new ActionListener(){
					public void actionPerformed(ActionEvent event){
						
						if(panelModelList.getSelectedValues().length!=0)
					    {
					        String view_name = JOptionPane.showInputDialog(desktop, 
					        	      "The current model is:  " + current.getName(), 
					                  "New View", JOptionPane.QUESTION_MESSAGE);
					        
					        if (view_name != null)
					        {
					        
					    	InterfacePrep intFrame = new InterfacePrep();
							intFrame.setModel(current);
							intFrame.setTitle(current.getName() + " - " + view_name);
							intFrame.setName(view_name);
						
							current.addObserver(intFrame);
							
							desktop.addInternalFrame(intFrame);
							
							// organiza as janelas
					    	TileViewCommand cmd = new TileViewCommand(desktop);
					    	cmd.execute();
					    	
							updateModelViewsNames();
							
							panelViewList.setListData(modelViewsName);
							panelViewList.repaint();
							panelView.setBorder(BorderFactory.createTitledBorder(" Views  [ " + nViewsMdl + " ]"));
							
							desktop.getDesktopTextArea().addText("A view  [ " + view_name + " ]  " +
									      "was added for the  [ " + current.getName() + " ]. ");
					        }// if button ok 
						}
						else{
							String message = "You must select a model!";
							JOptionPane.showMessageDialog(desktop, message, "Error Message", JOptionPane.ERROR_MESSAGE);
						}
					}
				});
        
        deleteModelBtn.addActionListener(
				new ActionListener(){
					public void actionPerformed(ActionEvent event){
						
						if(panelModelList.getSelectedValues().length!=0)
					    {
							desktop.closeModel(current);
							
					        if (desktop.getModelList().size() == 0)
					        	current = null;
					        else
					        	current = (GeoPrepModel)desktop.getModelList().get(0);
					
							updateModelNames();
							panelModelList.setListData(modelNames);
							panelModelList.repaint();
							
					        updateModelViewsNames();
							panelViewList.setListData(modelViewsName);
							panelViewList.repaint();
							panelView.setBorder(BorderFactory.createTitledBorder(" Views  [ " + nViewsDtk + " ] "));
						}
						else
						{
							String message = "You must select a model!";
							JOptionPane.showMessageDialog(desktop, message, "Error Message", JOptionPane.ERROR_MESSAGE);
						}
					}
				});            

        
        toFrontBtn.addActionListener(
				new ActionListener(){
					public void actionPerformed(ActionEvent event){
						
						if(panelViewList.getSelectedValues().length!=0)
						{
							int i = panelViewList.getSelectedIndex();
							String mdl_vn = modelViewsName[i];
							
							InterfacePrep view;
					        for (int k=0; k<nViewsDtk; k++)
					        {
					        	view = ((InterfacePrep)desktopViews[k]);
					        	if (mdl_vn.equalsIgnoreCase(view.getName()) == true)
					        	{
					        		view.toFront();
									desktop.getDesktop().repaint();
									desktop.getDesktopTextArea().addText("The view  [ " + view.getName() + " ]  was brought to front.");
					        	}
					        }
						}
						else
						{
							String message = "You must select a view!";
							JOptionPane.showMessageDialog(desktop, message, "Error Message", JOptionPane.ERROR_MESSAGE);
						}
					}
				});
        
        
        renameViewBtn.addActionListener(
				new ActionListener(){
					public void actionPerformed(ActionEvent event){
						
						if(panelViewList.getSelectedValues().length!=0)
						{
							int i = panelViewList.getSelectedIndex();
							String mdl_vn = modelViewsName[i];
							
							InterfacePrep view;
					        for (int k=0; k<nViewsDtk; k++)
					        {
					        	view = ((InterfacePrep)desktopViews[k]);
					        	if (mdl_vn.equalsIgnoreCase(view.getName()) == true)
					        	{
					            	String old_name = view.getName();
					            	String new_name = JOptionPane.showInputDialog(desktop, 
					            			       "Rename < " + old_name + " >  to:", 
					            			       "Rename the View", JOptionPane.QUESTION_MESSAGE);
					                if (new_name != null)
					                {
					            	   view.setName(new_name);
					            	   view.setTitle(current.getName() + " - " + new_name);
					            	   desktop.getDesktopTextArea().addText("The view  [ " + old_name + " ]  was renamed to:  " + new_name);
									   updateModelViewsNames();
									   panelViewList.setListData(modelViewsName);
									   panelViewList.repaint();
					                }
					               else
					            	   desktop.getDesktopTextArea().addText("Rename view command was canceled!");	
					                
								   desktop.getDesktop().repaint();
					        	}
					        }
						}
						else
						{
							String message = "You must select a view!";
							JOptionPane.showMessageDialog(desktop, message, "Error Message", JOptionPane.ERROR_MESSAGE);
						}
					}
				});        
        
        
        
        closeViewBtn.addActionListener(
				new ActionListener(){
					public void actionPerformed(ActionEvent event){
						if(panelViewList.getSelectedValues().length!=0)
					    {
							int i = panelViewList.getSelectedIndex();
							String mdl_vn = modelViewsName[i];
							
							InterfacePrep view;
							
					        for (int k=0; k<nViewsDtk; k++)
					        {
					        	view = ((InterfacePrep)desktopViews[k]);
					        	if (mdl_vn.equalsIgnoreCase(view.getName()) == true)
					        	{
									desktop.getDesktop().remove(view);
									desktop.getDesktop().repaint();
									view.getModel().deleteObserver(view);
									updateModelViewsNames();
									panelViewList.setListData(modelViewsName);
									panelViewList.repaint();
									panelView.setBorder(BorderFactory.createTitledBorder(" Views  [ " + nViewsMdl + " ] "));
									desktop.getDesktopTextArea().addText("A view  [ " + view.getName() + " ]  " +
										      "was removed from [ " + current.getName() + " ]. ");
					        	}
					        }
						}
						else
						{
							String message = "You must select a view!";
							JOptionPane.showMessageDialog(desktop, message, "Error Message", JOptionPane.ERROR_MESSAGE);
						}
					}
				}); 
        
        
        closeAllViewBtn.addActionListener(
				new ActionListener(){
					public void actionPerformed(ActionEvent event){
						if(panelModelList.getSelectedValues().length!=0)
					    {
							int i = panelModelList.getSelectedIndex();
					        current = (GeoPrepModel)desktop.getModelList().get(i);
					        
							InterfacePrep view;
							
					        for (int k=0; k<nViewsDtk; k++)
					        {
					        	view = ((InterfacePrep)desktopViews[k]);
					        	if (view.getModel().equals(current) == true)
					        	{
					        		desktop.getDesktop().remove(view);
					        	}
					        }				
					        current.deleteObservers();
					        desktop.getDesktop().repaint();
							updateModelViewsNames();
							panelViewList.setListData(modelViewsName);
							panelViewList.repaint();
							panelView.setBorder(BorderFactory.createTitledBorder(" Views  [ " + nViewsMdl + " ] "));
							desktop.getDesktopTextArea().addText("All views from  [ " + current.getName() + " ]  was closed.");
						}
						else
						{
							String message = "You must select a model!";
							JOptionPane.showMessageDialog(desktop, message, "Error Message", JOptionPane.ERROR_MESSAGE);
						}
					}
				});        
        
        
        panelModelList.addListSelectionListener(
               new ListSelectionListener() {
            	   public void valueChanged(ListSelectionEvent e) {

						if(panelModelList.getSelectedValues().length!=0)
					    {
							int i = panelModelList.getSelectedIndex();
					        current = (GeoPrepModel)desktop.getModelList().get(i);
					        updateModelViewsNames();
					        panelModelList.repaint();
							panelViewList.setListData(modelViewsName);
							panelViewList.repaint();
							panelView.setBorder(BorderFactory.createTitledBorder(" Views  [ " + nViewsMdl + " ] "));
						}
					}
				});        
        
        
    } // end of the constructor
    
//  ****************************************************************************  
    
    private void updateModelNames()
    {    	    	
   	   ArrayList modelList = new ArrayList();
       modelList = desktop.getModelList();
       
       nModels = modelList.size();
       
       modelNames = new String[nModels];
       GeoPrepModel temp;
       
       for(int i=0; i<nModels; i++)
       { 
       	temp = (GeoPrepModel)modelList.get(i);
       	modelNames[i] = temp.getName();
       }
   }    
    
//  ****************************************************************************
    
    private void updateModelViewsNames()
    {
        desktopViews = desktop.getDesktop().getAllFrames();
        nViewsDtk = desktopViews.length;

 	    // gets all observers of the current model
        if (current != null)
        	nViewsMdl = current.countObservers();
        else
        	nViewsMdl = 0;
        modelViewsName = new String[nViewsMdl];
        
        int j = 0;
        InterfacePrep view;
        
        for (int k=0; k<nViewsDtk; k++)
        {
        	view = ((InterfacePrep)desktopViews[k]);
        	if (view.getModel().equals(current) == true)
        	{
        		modelViewsName[j] = view.getName();
        		j++;
        	}
        }  
    }

//  ****************************************************************************   
     
     private JPanel getPanelModel()
     {
        panelModel.setLayout(new GridLayout(1,1,1,1));
        panelModel.setPreferredSize(new Dimension(200,150));
        panelModel.setBorder(BorderFactory.createTitledBorder(" Models "));
        
        this.updateModelNames();
        panelModelList = new JList(modelNames);
     	panelModelList.setSelectedIndex(0);
     	panelModelList.setSize(120,150);
     	panelModelList.setBackground(Color.WHITE);
     	panelModelList.setForeground(Color.BLUE);
     	panelModelList.setVisibleRowCount(5);
     	panelModelList.setFixedCellHeight(20);
     	panelModelList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
     	panelModelList.setAutoscrolls(true);
     	panelModelList.setAutoscrolls(true);
        panelScrollModel = new JScrollPane(panelModelList);
     	panelModel.add(panelScrollModel);
        
 		return panelModel;
     }  
     
//  **************************************************************************** 
     
     private JPanel getPanelView()
     {
        panelView.setLayout(new GridLayout(1,1,1,1));
        panelView.setPreferredSize(new Dimension(200,150));

        this.updateModelViewsNames();
        panelView.setBorder(BorderFactory.createTitledBorder(" Views  [ " + nViewsMdl + " ] "));
        panelViewList = new JList(modelViewsName);
        panelViewList.setSize(250,200);
      	panelViewList.setBackground(Color.WHITE);
        panelViewList.setForeground(Color.BLACK);
      	panelViewList.setVisibleRowCount(5);
      	panelViewList.setFixedCellHeight(20);
      	panelViewList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
      	panelViewList.setAutoscrolls(true); 
      	panelScrollView  = new JScrollPane(panelViewList);
      	panelView.add(panelScrollView);

 		return panelView;    	 
     }
     
//  ****************************************************************************   
     
     private JPanel getPanelButton()
     {   

 		panelButton.setLayout(new GridLayout(2,3,5,5));
		panelButton.setPreferredSize(new Dimension(250,65));
		panelButton.setBorder(BorderFactory.createTitledBorder(""));
		
		addViewBtn = new JButton("Add a View...");
		addViewBtn.setToolTipText("Add a new view for the selected Model.");
		
		toFrontBtn = new JButton("Bring to Front");
		toFrontBtn.setToolTipText("Brings to front the selected view.");
		
		renameViewBtn = new JButton("Rename...");
		renameViewBtn.setToolTipText("Rename the selected view.");

		closeViewBtn = new JButton("Close");
		closeViewBtn.setToolTipText("Closes the selected view.");
		
		closeAllViewBtn = new JButton("Close all");
		closeAllViewBtn.setToolTipText("Closes all views of a selected model.");
		
		deleteModelBtn = new JButton("Delete the Model");
		deleteModelBtn.setToolTipText("Deletes the Model and its Views.");
		
		panelButton.add(addViewBtn);
		panelButton.add(toFrontBtn);
		panelButton.add(renameViewBtn);
		panelButton.add(closeViewBtn);
		panelButton.add(closeAllViewBtn);
		panelButton.add(deleteModelBtn);

  		return panelButton;
     }
	
//  ****************************************************************************
    
    public int showDialog() {
        return super.showDialog(desktop , "Models and Views");
    }
	
//  ****************************************************************************
	
    /**
     * This method is executed on OK button click.
     *
     */
    public void approvedPerform() {
        try {
			
        } catch (Exception err) {
            Toolkit.getDefaultToolkit().beep();
            this.setVisible(false);
        }
    }
        
//  ****************************************************************************
    
    /**
     * Sets the number formater
     */
    private void setUpFormat() {
        numberFormat = (DecimalFormat)NumberFormat.getNumberInstance(Locale.UK);
        numberFormat.setMaximumFractionDigits(3);
    }
	
//  ****************************************************************************
}
